/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package base;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import tal.drivechain.matchers.VarMatcher;
import tal.drivechain.plugin.Channel;
import tal.drivechain.plugin.Module;
import tal.drivechain.variable.SetProperty;
import tal.drivechain.variable.Variable;

/*
 * Execute.java
 *
 * Created on December 5, 2007, 1:45 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author Main
 */
public class Execute extends Module {
    List<Object[]> triggerFilename;

    @Override
    public void setupProperties() {
        try {
            setTriggerFilename(props.getProperty("triggerFilename"), null);
        } catch (IllegalArgumentException ie) {
            log(ie.getMessage(), MSG.ERROR);
        }
    }

    public void setTriggerFilename(Object value, SetProperty.Flag flag) {
        if (triggerFilename==null) triggerFilename = new ArrayList();
        if (flag == SetProperty.Flag.REPLACE)
            triggerFilename = (List)value;
        else
            triggerFilename.addAll((List)value);
    } public Object getTriggerFilename() { return triggerFilename; }
    
    public void execute(String... filenames) {
        for (String filename : filenames) {
            execute(filename);
        }
    }
    
    @Override
    protected void msgReceived(Variable in, long timestamp, Channel channel) {
        for (Object[] item : triggerFilename) {
            VarMatcher trigger = (VarMatcher)item[0];
            if (trigger.matches(in, channel, this)) {
                Variable filename = (Variable)item[1];
                execute(filename.getValue(this).toString());
            }
        }
    }

    private void execute(String f) {
        try {
            Runtime.getRuntime().exec(f);
            if (debugFlag)
                log("Executing " + f, MSG.DEBUG);
        } catch (IOException ex) {
            log("Error while trying to execute " + f + " (" + ex.getMessage() + ")", MSG.WARNING);
        }

    }
}
